import { useEffect, useState, useRef } from 'react';
import { useParams, Link } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeHighlight from 'rehype-highlight';
import rehypeRaw from 'rehype-raw';
import { ArrowLeft, Calendar, User, Clock, List, ChevronRight, Copy, Check } from 'lucide-react';
import { useLanguage } from '../contexts/LanguageContext';
import { useLocalizedLink } from '../hooks/useLocalizedLink';
// 导入两套主题：浅色和深色
import 'highlight.js/styles/github.css'; // 浅色模式
import 'highlight.js/styles/github-dark.css'; // 深色模式

interface TocItem {
  id: string;
  text: string;
  level: number;
}

// 阅读进度组件
function ReadingProgress() {
  const [progress, setProgress] = useState(0);
  const { language } = useLanguage();

  useEffect(() => {
    const updateProgress = () => {
      const scrollTop = window.scrollY;
      const docHeight = document.documentElement.scrollHeight;
      const winHeight = window.innerHeight;
      const scrollPercent = scrollTop / (docHeight - winHeight);
      const scrollPercentRounded = Math.round(scrollPercent * 100);
      
      const finalProgress = Math.min(100, Math.max(0, scrollPercentRounded));
      
      if (scrollTop + winHeight >= docHeight - 50) {
        setProgress(100);
      } else {
        setProgress(finalProgress);
      }
    };

    window.addEventListener('scroll', updateProgress);
    updateProgress();

    return () => window.removeEventListener('scroll', updateProgress);
  }, []);

  return (
    <div className="mt-4 bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 p-4 shadow-sm">
      <div className="flex items-center justify-between text-xs text-gray-600 dark:text-gray-400 mb-2">
        <span>{language === 'zh-CN' ? '阅读进度' : 'Reading Progress'}</span>
        <span>{progress}%</span>
      </div>
      <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
        <div 
          className="bg-[#00d4ff] h-2 rounded-full transition-all duration-300"
          style={{ width: `${progress}%` }}
        />
      </div>
    </div>
  );
}

const BlogPost = () => {
  const { slug } = useParams<{ slug: string }>();
  const [content, setContent] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [toc, setToc] = useState<TocItem[]>([]);
  const [activeId, setActiveId] = useState<string>('');
  const [tocOpen, setTocOpen] = useState(false);
  const [tocCollapsed, setTocCollapsed] = useState(false);
  const [copiedStates, setCopiedStates] = useState<{[key: string]: boolean}>({});
  const { language } = useLanguage();
  const { getLink } = useLocalizedLink();
  const articleRef = useRef<HTMLElement>(null);

  // 博客元数据映射
  const blogMeta: Record<string, { date: string; author: string; readTime: string; title: string }> = {
    'ipv6-future-trends': {
      date: '2023-08-15',
      author: language === 'zh-CN' ? '张工' : 'Zhang Gong',
      readTime: language === 'zh-CN' ? '8 分钟' : '8 min read',
      title: language === 'zh-CN' ? 'IPv6代理技术的未来发展趋势' : 'Future Trends in IPv6 Proxy Technology',
    },
    'api-integration': {
      date: '2023-08-10',
      author: language === 'zh-CN' ? '李工' : 'Li Gong',
      readTime: language === 'zh-CN' ? '12 分钟' : '12 min read',
      title: language === 'zh-CN' ? '如何高效集成kernelProxy API' : 'How to Efficiently Integrate kernelProxy API',
    },
    'web-scraping-best-practices': {
      date: '2023-08-05',
      author: language === 'zh-CN' ? '王工' : 'Wang Gong',
      readTime: language === 'zh-CN' ? '15 分钟' : '15 min read',
      title: language === 'zh-CN' ? 'Web数据采集最佳实践指南' : 'Web Scraping Best Practices Guide',
    },
  };

  const meta = blogMeta[slug || ''] || {
    date: '',
    author: '',
    readTime: '',
    title: '',
  };

  useEffect(() => {
    const loadMarkdown = async () => {
      try {
        setLoading(true);
        setError(null);
        
        // 尝试加载对应语言的markdown文件
        let mdPath = `/blog/${slug}.md`;
        if (language === 'zh-CN') {
          // 如果有中文版本，优先加载
          try {
            const zhResponse = await fetch(`/blog/${slug}.zh-CN.md`);
            if (zhResponse.ok) {
              mdPath = `/blog/${slug}.zh-CN.md`;
            }
          } catch (e) {
            // 如果没有中文版本，使用默认版本
          }
        }

        const response = await fetch(mdPath);
        if (!response.ok) {
          throw new Error('Blog post not found');
        }
        const text = await response.text();
        setContent(text);
        
        // 提取目录
        extractToc(text);
      } catch (err) {
        setError(language === 'zh-CN' ? '无法加载博客文章' : 'Failed to load blog post');
        console.error('Error loading markdown:', err);
      } finally {
        setLoading(false);
      }
    };

    if (slug) {
      loadMarkdown();
    }
  }, [slug, language]);

  // 提取目录
  const extractToc = (markdown: string) => {
    const headingRegex = /^(#{1,3})\s+(.+)$/gm;
    const headings: TocItem[] = [];
    let match;

    while ((match = headingRegex.exec(markdown)) !== null) {
      const level = match[1].length;
      const text = match[2].replace(/\*\*/g, '').replace(/\*/g, '').trim();
      const id = text
        .toLowerCase()
        .replace(/[^\w\u4e00-\u9fa5]+/g, '-')
        .replace(/^-+|-+$/g, '');
      
      headings.push({ id, text, level });
    }

    setToc(headings);
  };

  // 监听滚动，高亮当前标题
  useEffect(() => {
    const handleScroll = () => {
      if (!articleRef.current) return;

      const headings = articleRef.current.querySelectorAll('h1, h2, h3');
      const scrollPosition = window.scrollY + 100;

      let currentId = '';
      headings.forEach((heading) => {
        const element = heading as HTMLElement;
        if (element.offsetTop <= scrollPosition) {
          currentId = element.id;
        }
      });

      setActiveId(currentId);
    };

    window.addEventListener('scroll', handleScroll);
    handleScroll(); // 初始调用

    return () => window.removeEventListener('scroll', handleScroll);
  }, [content]);

  const scrollToHeading = (id: string) => {
    const element = document.getElementById(id);
    if (element) {
      const offset = 80;
      const elementPosition = element.getBoundingClientRect().top;
      const offsetPosition = elementPosition + window.pageYOffset - offset;

      window.scrollTo({
        top: offsetPosition,
        behavior: 'smooth',
      });
    }
    setTocOpen(false);
  };

  // 复制代码到剪贴板
  const handleCopyCode = async (code: string, blockId: string) => {
    try {
      await navigator.clipboard.writeText(code.trim());
      setCopiedStates(prev => ({ ...prev, [blockId]: true }));
      
      setTimeout(() => {
        setCopiedStates(prev => ({ ...prev, [blockId]: false }));
      }, 2000);
    } catch (err) {
      console.error('Failed to copy code:', err);
    }
  };

  // 生成代码块 ID
  const generateCodeBlockId = (code: string): string => {
    let hash = 0;
    for (let i = 0; i < code.length; i++) {
      const char = code.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash;
    }
    return `code-${Math.abs(hash).toString(36)}`;
  };

  // 获取语言颜色
  const getLanguageColor = (language: string): string => {
    const colors: {[key: string]: string} = {
      'javascript': 'text-yellow-600 dark:text-yellow-400',
      'typescript': 'text-blue-600 dark:text-blue-400',
      'python': 'text-green-600 dark:text-green-400',
      'java': 'text-orange-600 dark:text-orange-400',
      'css': 'text-blue-500 dark:text-blue-300',
      'html': 'text-red-600 dark:text-red-400',
      'json': 'text-gray-600 dark:text-gray-400',
      'bash': 'text-green-700 dark:text-green-300',
      'shell': 'text-green-700 dark:text-green-300',
      'sql': 'text-indigo-600 dark:text-indigo-400',
    };
    return colors[language.toLowerCase()] || 'text-gray-600 dark:text-gray-400';
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-white dark:bg-gray-900 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#00d4ff] mx-auto mb-4"></div>
          <p className="text-gray-600 dark:text-gray-400">
            {language === 'zh-CN' ? '加载中...' : 'Loading...'}
          </p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-white dark:bg-gray-900 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-4xl font-bold text-gray-800 dark:text-white mb-4">404</h1>
          <p className="text-gray-600 dark:text-gray-400 mb-8">{error}</p>
          <Link
            to={getLink('/blog')}
            className="inline-flex items-center text-[#00d4ff] hover:underline"
          >
            <ArrowLeft size={16} className="mr-2" />
            {language === 'zh-CN' ? '返回博客列表' : 'Back to Blog'}
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full bg-white dark:bg-gray-900 transition-colors duration-300">
      {/* Header */}
      <section className="bg-gradient-to-b from-[#0f1c3f] to-[#1a2b4f] dark:from-gray-800 dark:to-gray-900 text-white py-12 transition-colors duration-300 border-b border-gray-700/30">
        <div className="container mx-auto px-4 max-w-7xl">
          <Link
            to={getLink('/blog')}
            className="inline-flex items-center text-gray-300 hover:text-white mb-6 transition-colors group"
          >
            <ArrowLeft size={16} className="mr-2 group-hover:-translate-x-1 transition-transform" />
            {language === 'zh-CN' ? '返回博客' : 'Back to Blog'}
          </Link>
          <h1 className="text-3xl md:text-5xl font-bold mb-6 leading-tight">{meta.title}</h1>
          <div className="flex flex-wrap items-center gap-6 text-sm text-gray-300">
            <div className="flex items-center gap-2">
              <div className="w-8 h-8 rounded-full bg-gradient-to-br from-[#00d4ff] to-[#0099cc] flex items-center justify-center">
                <User size={16} className="text-white" />
              </div>
              <span>{meta.author}</span>
            </div>
            <div className="flex items-center gap-2">
              <Calendar size={16} className="text-[#00d4ff]" />
              <span>{meta.date}</span>
            </div>
            <div className="flex items-center gap-2">
              <Clock size={16} className="text-[#00d4ff]" />
              <span>{meta.readTime}</span>
            </div>
          </div>
        </div>
      </section>

      {/* Content with TOC */}
      <div className="container mx-auto px-4 py-12 max-w-7xl">
        <div className="flex gap-8 lg:gap-12 relative">
          {/* Main Content */}
          <article 
            ref={articleRef}
            className="flex-1 min-w-0"
          >
            {/* Mobile TOC Button */}
            <button
              onClick={() => setTocOpen(!tocOpen)}
              className="lg:hidden mb-6 flex items-center gap-2 px-4 py-2 bg-gray-100 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
            >
              <List size={18} />
              <span className="text-sm font-medium">
                {language === 'zh-CN' ? '目录' : 'Table of Contents'}
              </span>
            </button>

            {/* Mobile TOC Dropdown */}
            {tocOpen && (
              <div className="lg:hidden mb-6 p-4 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700">
                <nav className="space-y-2">
                  {toc.map((item) => (
                    <button
                      key={item.id}
                      onClick={() => scrollToHeading(item.id)}
                      className={`block w-full text-left text-sm transition-colors ${
                        activeId === item.id
                          ? 'text-[#00d4ff] font-medium'
                          : 'text-gray-600 dark:text-gray-400 hover:text-[#00d4ff]'
                      }`}
                      style={{ paddingLeft: `${(item.level - 1) * 12}px` }}
                    >
                      {item.text}
                    </button>
                  ))}
                </nav>
              </div>
            )}

            {/* GitHub-style Article Container */}
            <div className="bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm overflow-hidden">
              <div className="p-6 md:p-8 lg:p-12">
                <div className="
                  prose prose-lg dark:prose-invert max-w-none
                  prose-headings:scroll-mt-20
                  prose-headings:font-bold
                  prose-h1:text-4xl prose-h1:mb-4 prose-h1:pb-3 prose-h1:border-b prose-h1:border-gray-200 dark:prose-h1:border-gray-800
                  prose-h2:text-3xl prose-h2:mt-12 prose-h2:mb-4 prose-h2:pb-2 prose-h2:border-b prose-h2:border-gray-200 dark:prose-h2:border-gray-800
                  prose-h3:text-2xl prose-h3:mt-8 prose-h3:mb-3
                  prose-p:text-gray-700 dark:prose-p:text-gray-300 prose-p:leading-7 prose-p:my-4
                  prose-a:text-[#00d4ff] prose-a:no-underline hover:prose-a:underline prose-a:font-medium
                  prose-strong:text-gray-900 dark:prose-strong:text-white prose-strong:font-semibold
                  prose-em:text-gray-700 dark:prose-em:text-gray-300
                  prose-code:text-[#e83e8c] dark:prose-code:text-[#ff6b9d] prose-code:bg-gray-100 dark:prose-code:bg-gray-800
                  prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-sm prose-code:font-mono
                  prose-code:before:content-[''] prose-code:after:content-['']
                  prose-pre:bg-transparent prose-pre:p-0 prose-pre:m-0
                  prose-blockquote:border-l-4 prose-blockquote:border-[#00d4ff]
                  prose-blockquote:bg-gray-50 dark:prose-blockquote:bg-gray-800/50
                  prose-blockquote:py-2 prose-blockquote:px-4
                  prose-blockquote:my-6 prose-blockquote:rounded-r
                  prose-blockquote:not-italic
                  prose-hr:border-gray-300 dark:prose-hr:border-gray-700 prose-hr:my-8
                  prose-ul:my-4 prose-ul:list-disc
                  prose-ol:my-4 prose-ol:list-decimal
                  prose-li:text-gray-700 dark:prose-li:text-gray-300 prose-li:my-2
                  prose-li:marker:text-gray-500 dark:prose-li:marker:text-gray-500
                  prose-table:my-6 prose-table:border-collapse
                  prose-th:bg-gray-100 dark:prose-th:bg-gray-800 prose-th:p-3 prose-th:border prose-th:border-gray-300 dark:prose-th:border-gray-700
                  prose-td:p-3 prose-td:border prose-td:border-gray-300 dark:prose-td:border-gray-700
                  prose-img:rounded-lg prose-img:shadow-md prose-img:my-6
                ">
                  <ReactMarkdown
                    remarkPlugins={[remarkGfm]}
                    rehypePlugins={[rehypeHighlight, rehypeRaw]}
                    components={{
                      h1: ({ children, ...props }: any) => {
                        const text = String(children);
                        const id = text.toLowerCase().replace(/[^\w\u4e00-\u9fa5]+/g, '-').replace(/^-+|-+$/g, '');
                        return (
                          <h1 id={id} className="scroll-mt-20" {...props}>
                            {children}
                          </h1>
                        );
                      },
                      h2: ({ children, ...props }: any) => {
                        const text = String(children);
                        const id = text.toLowerCase().replace(/[^\w\u4e00-\u9fa5]+/g, '-').replace(/^-+|-+$/g, '');
                        return (
                          <h2 id={id} className="scroll-mt-20" {...props}>
                            {children}
                          </h2>
                        );
                      },
                      h3: ({ children, ...props }: any) => {
                        const text = String(children);
                        const id = text.toLowerCase().replace(/[^\w\u4e00-\u9fa5]+/g, '-').replace(/^-+|-+$/g, '');
                        return (
                          <h3 id={id} className="scroll-mt-20" {...props}>
                            {children}
                          </h3>
                        );
                      },
                      // 自定义代码块
                      pre({ children, className, ...props }: any) {
                        // 提取代码内容
                        const extractAllText = (element: any): string => {
                          if (typeof element === 'string') return element;
                          if (element?.props?.children) {
                            if (typeof element.props.children === 'string') {
                              return element.props.children;
                            }
                            if (Array.isArray(element.props.children)) {
                              return element.props.children.map(extractAllText).join('');
                            }
                            return extractAllText(element.props.children);
                          }
                          return '';
                        };

                        let codeText = '';
                        if (Array.isArray(children)) {
                          codeText = children.map(extractAllText).join('');
                        } else {
                          codeText = extractAllText(children);
                        }

                        // 提取语言信息 - 从 code 元素的 className 中提取
                        let language = '';
                        
                        // 直接从 children 获取（children 通常就是 code 元素）
                        const codeElement = children;

                        // 从 code 元素的 props 中提取 className
                        if (codeElement?.props?.className) {
                          const match = /language-(\w+)/.exec(codeElement.props.className);
                          if (match) {
                            language = match[1];
                          }
                        }
                        
                        // 方法2: 从 pre 元素的 className 中提取（作为备用）
                        if (!language && className) {
                          const match = /language-(\w+)/.exec(className);
                          if (match) {
                            language = match[1];
                          }
                        }

                        const blockId = generateCodeBlockId(codeText);
                        const isCopied = copiedStates[blockId] || false;
                        const codeLines = codeText.trim().split('\n');
                        const showLineNumbers = codeLines.length > 3;

                        return (
                          <div className="my-6 rounded-lg border border-gray-300 dark:border-gray-700 overflow-hidden shadow-sm">
                            {/* 代码块头部 - macOS 风格 */}
                            <div className="bg-gray-100 dark:bg-gray-800 px-4 py-2.5 border-b border-gray-300 dark:border-gray-700 flex justify-between items-center">
                              <div className="flex items-center gap-2">
                                <div className="w-3 h-3 bg-red-500 rounded-full"></div>
                                <div className="w-3 h-3 bg-yellow-500 rounded-full"></div>
                                <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                                {language && (
                                  <span className={`text-xs font-semibold ml-2 select-none ${getLanguageColor(language)}`}>
                                    {language.toUpperCase()}
                                  </span>
                                )}
                              </div>
                              <button
                                type="button"
                                onClick={() => handleCopyCode(codeText, blockId)}
                                className={`flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium select-none rounded-md transition-all duration-300 ${
                                  isCopied 
                                    ? 'text-green-600 dark:text-green-400 bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800' 
                                    : 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-700 border border-transparent'
                                }`}
                                title={isCopied ? (language === 'zh-CN' ? '已复制' : 'Copied') : (language === 'zh-CN' ? '复制代码' : 'Copy code')}
                                disabled={isCopied}
                              >
                                {isCopied ? (
                                  <>
                                    <Check size={14} className="text-green-500 dark:text-green-400" />
                                    <span className="hidden sm:inline text-green-600 dark:text-green-400">
                                      {language === 'zh-CN' ? '已复制' : 'Copied'}
                                    </span>
                                  </>
                                ) : (
                                  <>
                                    <Copy size={14} />
                                    <span className="hidden sm:inline">
                                      {language === 'zh-CN' ? '复制' : 'Copy'}
                                    </span>
                                  </>
                                )}
                              </button>
                            </div>
                            {/* 代码内容 */}
                            <div className="bg-[#f6f8fa] dark:bg-[#0d1117] relative">
                              {showLineNumbers ? (
                                <div className="flex">
                                  {/* 行号列 */}
                                  <div className="flex-shrink-0 bg-[#f0f3f6] dark:bg-[#161b22] border-r border-gray-200 dark:border-gray-700 select-none">
                                    <pre 
                                      className="m-0 text-center"
                                      style={{
                                        fontFamily: 'Consolas, Monaco, "Courier New", monospace',
                                        fontSize: '12px',
                                        lineHeight: '24px',
                                        paddingTop: '16px',
                                        paddingBottom: '16px',
                                        paddingLeft: '12px',
                                        paddingRight: '12px',
                                        minWidth: '48px',
                                        background: 'transparent'
                                      }}
                                    >
                                      {codeLines.map((_: string, index: number) => (
                                        <div key={index} className="text-gray-500 dark:text-gray-500">
                                          {index + 1}
                                        </div>
                                      ))}
                                    </pre>
                                  </div>
                                  {/* 代码列 */}
                                  <div className="flex-1 overflow-hidden">
                                    <pre 
                                      className={`m-0 text-sm ${className || ''}`}
                                      {...props}
                                      style={{
                                        fontFamily: 'Consolas, Monaco, "Courier New", monospace',
                                        fontSize: '14px',
                                        lineHeight: '24px',
                                        background: 'transparent',
                                        whiteSpace: 'pre',
                                        overflowX: 'auto',
                                        tabSize: 2,
                                        paddingTop: '16px',
                                        paddingBottom: '16px',
                                        paddingLeft: '16px',
                                        paddingRight: '16px'
                                      }}
                                    >
                                      {children}
                                    </pre>
                                  </div>
                                </div>
                              ) : (
                                <pre 
                                  className={`p-4 text-sm m-0 ${className || ''}`}
                                  {...props}
                                  style={{
                                    fontFamily: 'Consolas, Monaco, "Courier New", monospace',
                                    fontSize: '14px',
                                    lineHeight: '24px',
                                    background: 'transparent',
                                    whiteSpace: 'pre',
                                    overflowX: 'auto',
                                    tabSize: 2
                                  }}
                                >
                                  {children}
                                </pre>
                              )}
                            </div>
                          </div>
                        );
                      },
                      // 内联代码
                      code({ className, children, ...props }: any) {
                        if (className?.includes('language-')) {
                          return <code className={className} {...props}>{children}</code>;
                        }
                        return (
                          <code
                            className="bg-gray-100 dark:bg-gray-800 text-pink-600 dark:text-pink-400 px-1.5 py-0.5 rounded font-mono text-sm"
                            {...props}
                          >
                            {children}
                          </code>
                        );
                      },
                      // 表格
                      table({ children }: any) {
                        return (
                          <div className="overflow-x-auto my-6 rounded-lg border border-gray-300 dark:border-gray-700 shadow-sm">
                            <table className="min-w-full border-collapse bg-white dark:bg-gray-800 table-auto">
                              {children}
                            </table>
                          </div>
                        );
                      },
                      thead({ children }: any) {
                        return (
                          <thead className="bg-gray-100 dark:bg-gray-700 border-b-2 border-gray-300 dark:border-gray-600">
                            {children}
                          </thead>
                        );
                      },
                      th({ children }: any) {
                        return (
                          <th className="px-6 py-4 text-left text-sm font-bold text-gray-900 dark:text-gray-100 border-r border-gray-200 dark:border-gray-600 last:border-r-0">
                            {children}
                          </th>
                        );
                      },
                      td({ children }: any) {
                        return (
                          <td className="px-6 py-4 text-sm text-gray-700 dark:text-gray-300 border-b border-gray-200 dark:border-gray-600 border-r border-gray-200 dark:border-gray-600 last:border-r-0">
                            {children}
                          </td>
                        );
                      },
                      // 引用块
                      blockquote({ children }: any) {
                        return (
                          <blockquote className="border-l-4 border-[#00d4ff] pl-6 py-4 my-6 bg-blue-50 dark:bg-blue-900/20 rounded-r-lg">
                            <div className="text-gray-700 dark:text-gray-300">
                              {children}
                            </div>
                          </blockquote>
                        );
                      },
                      // 链接
                      a({ children, href }: any) {
                        return (
                          <a 
                            href={href} 
                            className="text-[#00d4ff] hover:text-[#00b8e6] underline transition-colors"
                            target="_blank"
                            rel="noopener noreferrer"
                          >
                            {children}
                          </a>
                        );
                      },
                    }}
                  >
                    {content}
                  </ReactMarkdown>
                </div>
              </div>
            </div>
          </article>

          {/* Desktop TOC Sidebar */}
          {toc.length > 0 && (
            <aside className="hidden lg:block w-64 flex-shrink-0">
              <div className="sticky top-24 max-h-[calc(100vh-8rem)] flex flex-col gap-4">
                {/* 目录 */}
                <div className="bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm max-h-[60vh] flex flex-col">
                  {/* 头部 */}
                  <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50">
                    <div className="flex items-center gap-2">
                      <List size={16} className="text-[#00d4ff]" />
                      <h3 className="text-sm font-semibold text-gray-900 dark:text-white">
                        {language === 'zh-CN' ? '目录' : 'Table of Contents'}
                      </h3>
                    </div>
                    <button
                      onClick={() => setTocCollapsed(!tocCollapsed)}
                      className="p-1 rounded-md hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                    >
                      <ChevronRight 
                        size={16}
                        className={`text-gray-600 dark:text-gray-400 transition-transform ${
                          tocCollapsed ? 'rotate-0' : 'rotate-90'
                        }`} 
                      />
                    </button>
                  </div>
                  
                  {/* 目录内容 */}
                  {!tocCollapsed && (
                    <div className="flex-1 overflow-y-auto custom-scrollbar">
                      <nav className="p-2">
                        <ul className="space-y-1">
                          {toc.map((item) => {
                            const isActive = activeId === item.id;
                            const marginLeft = (item.level - 1) * 12;
                            
                            return (
                              <li key={item.id}>
                                <button
                                  onClick={() => scrollToHeading(item.id)}
                                  className={`
                                    w-full text-left px-3 py-2 rounded-md text-sm transition-all duration-200
                                    hover:bg-gray-100 dark:hover:bg-gray-800
                                    ${isActive 
                                      ? 'bg-blue-50 dark:bg-blue-900/30 text-[#00d4ff] border-l-2 border-[#00d4ff] font-medium' 
                                      : 'text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100'
                                    }
                                  `}
                                  style={{ marginLeft: `${marginLeft}px` }}
                                  title={item.text}
                                >
                                  <span className="block truncate">
                                    {item.text}
                                  </span>
                                </button>
                              </li>
                            );
                          })}
                        </ul>
                      </nav>
                    </div>
                  )}
                </div>
                
                {/* 阅读进度 */}
                <ReadingProgress />
              </div>
            </aside>
          )}
        </div>
      </div>

      {/* Related Posts */}
      <section className="py-12 bg-gray-50 dark:bg-gray-800/50 transition-colors duration-300">
        <div className="container mx-auto px-4">
          <div className="max-w-4xl mx-auto">
            <h2 className="text-2xl font-bold text-[#0f1c3f] dark:text-white mb-6">
              {language === 'zh-CN' ? '相关文章' : 'Related Posts'}
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {Object.entries(blogMeta)
                .filter(([key]) => key !== slug)
                .slice(0, 2)
                .map(([key, post]) => (
                  <Link
                    key={key}
                    to={getLink(`/blog/${key}`)}
                    className="group block p-6 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-[#00d4ff] dark:hover:border-[#00d4ff] hover:shadow-xl hover:-translate-y-1 transition-all duration-300"
                  >
                    <h3 className="text-xl font-bold text-[#0f1c3f] dark:text-white group-hover:text-[#00d4ff] dark:group-hover:text-[#00d4ff] mb-2 transition-colors duration-300">
                      {post.title}
                    </h3>
                    <div className="flex items-center text-sm text-gray-500 dark:text-gray-400 group-hover:text-gray-700 dark:group-hover:text-gray-300 transition-colors duration-300">
                      <Calendar size={14} className="mr-1" />
                      <span>{post.date}</span>
                      <span className="mx-2">•</span>
                      <span>{post.readTime}</span>
                    </div>
                  </Link>
                ))}
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

export default BlogPost;
